package org.yray.netty.v5;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.bytes.ByteArrayDecoder;
import io.netty.handler.codec.string.StringDecoder;


public class NettyClient {
    public static void main(String[] args) {
        System.out.println("客户端启动....");
        try {
            // 创建负责接收客户端连接
            NioEventLoopGroup pGroup = new NioEventLoopGroup();
            Bootstrap b = new Bootstrap();
            b.group(pGroup).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel sc) throws Exception {
                    // 设置返回类型为String类型
                    sc.pipeline().addLast(new StringDecoder());
                    sc.pipeline().addLast(new ClientHandler());
                }
            });

            ChannelFuture cf = b.connect("127.0.0.1",8899).sync();
            cf.channel().writeAndFlush(Unpooled.copiedBuffer("msg".getBytes()));
            cf.channel().closeFuture().sync();
            pGroup.shutdownGracefully();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


}
